package com.fierce.cloud.ota.service.impl;

import com.fierce.cloud.core.common.service.BaseService;
import com.fierce.cloud.core.web.ResultGenerator;
import com.fierce.cloud.core.web.responseDto.Response;
import com.fierce.cloud.exception.CustomException;
import com.fierce.cloud.ota.dao.VersionInfoMapper;
import com.fierce.cloud.ota.model.VersionInfo;
import com.fierce.cloud.ota.service.VersionInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author: Fierce
 * @Date: 2021/2/26 11:39
 */
@Service
public class VersionInfoServiceImpl extends BaseService<VersionInfo> implements VersionInfoService {

    @Autowired
    VersionInfoMapper versionInfoMapper;

    @Override
    public VersionInfo getNewestVersionByAppId(Long appId) {
        return versionInfoMapper.selectNewestVersionByAppId(appId);
    }

    @Override
    public String versionUpload(String versionName, MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new CustomException("未选择上传的版本");
        }
        String filePath = new File("upload/version").getAbsolutePath();
        File fileUpload = new File(filePath);
        if (!fileUpload.exists()) {
            fileUpload.mkdirs();
        }

        fileUpload = new File(filePath, versionName);
        if (fileUpload.exists()) {
            throw new CustomException("上传的版本已存在");
        }

        try {
            file.transferTo(fileUpload);

            return fileUpload.getAbsolutePath();
        } catch (IOException e) {
            throw new CustomException("上传版本到服务器失败：" + e.toString());
        }
    }

    @Override
    public void versionDownload(String name, HttpServletResponse response) {
        File file = new File("upload" + File.separator + "version" + File.separator + name);

        if (!file.exists()) {
            throw new CustomException(name + "文件不存在");
        }
        response.setContentType("application/octet-stream");
        response.setContentLength((int) file.length());
        response.addHeader("Content-Disposition", "attachment;fileName=" + name);

        byte[] buffer = new byte[1024];
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis)) {

            OutputStream os = response.getOutputStream();

            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
